from PyQt6.QtCore import QTimer, QSize, QEventLoop
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QVBoxLayout
from qfluentwidgets import FluentTitleBar, isDarkTheme, SplashScreen
from qfluentwidgets.common.animation import BackgroundAnimationWidget
from qfluentwidgets.components.widgets.frameless_window import FramelessWindow

from ui.SelfThemeListener import SelfThemeListener


class MainWindow(BackgroundAnimationWidget, FramelessWindow):
    """
    主窗口类
    """

    def __init__(self, title: str, icon: QIcon):
        super().__init__()
        # 创建主题监听器
        self.themeListener = SelfThemeListener(self)
        self.themeListener.themeChanged.connect(self.updateTitleBar)

        self.setup_ui(title, icon)

        self.splashScreen = SplashScreen(self.windowIcon(), self)
        self.splashScreen.setIconSize(QSize(102, 102))

        self.show()

        self.createSubInterface()

        self.splashScreen.finish()

        self.themeListener.start()

    def setup_ui(self, title: str, icon: QIcon) -> None:
        """标题ui"""
        self.setWindowIcon(icon)
        self.main_layout = QVBoxLayout()
        self.main_layout.setContentsMargins(0, 50, 0, 0)
        self.setLayout(self.main_layout)

        title_bar = FluentTitleBar(self)
        title_bar.iconLabel.setFixedSize(24, 24)
        title_bar.iconLabel.setPixmap(QIcon(icon).pixmap(24, 24))
        title_bar.hBoxLayout.setContentsMargins(18, 0, 0, 0)
        title_bar.setTitle(title)
        self.setTitleBar(title_bar)

    def createSubInterface(self):
        loop = QEventLoop(self)
        QTimer.singleShot(3000, loop.quit)
        loop.exec()

    def closeEvent(self, e):
        # 停止监听器线程
        self.themeListener.terminate()
        self.themeListener.deleteLater()
        super().closeEvent(e)

    def _onThemeChangedFinished(self):
        super()._onThemeChangedFinished()

        # 云母特效启用时需要增加重试机制
        if self.isMicaEffectEnabled():
            QTimer.singleShot(100, lambda: self.windowEffect.setMicaEffect(self.winId(), isDarkTheme()))

    def updateTitleBar(self, theme: str):
        if theme.lower() == 'dark':
            self.titleBar.titleLabel.setStyleSheet("color: white;")
        elif theme.lower() == 'light':
            self.titleBar.titleLabel.setStyleSheet("color: black;")
